<template>
    <div>
        <div>
            <el-card>
                <el-button type="success" @click='addStaMsg'>新增站内信</el-button>
            </el-card>
        </div>

        <div class="container">
            <el-tabs v-model="message">
                <el-tab-pane :label="`未读消息(${unreadNum})`" name="first" @click='initUnReadList'>
                    <el-table :data="unread" :show-header="false" style="width: 100%; height: 500px;">
                        <el-table-column v-if='false'>
                            <template slot-scope='scope'>
                                <span>{{scope.row.id}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column>
                            <template slot-scope="scope">
                                <span class="message-title">{{scope.row.title}}</span>
                            </template>
                        </el-table-column>

                        <el-table-column prop='priority'>
                            <template slot-scope="scope">
                                <el-tag v-if='scope.row.priority === 1' type='success'>普通</el-tag>
                                <el-tag v-if='scope.row.priority === 2' type='normal'>重要</el-tag>
                                <el-tag v-if='scope.row.priority === 3' type='danger'>紧急</el-tag>
                            </template>
                        </el-table-column>

                        <el-table-column prop='msgType'>
                            <template slot-scope="scope">
                                <el-tag v-if='scope.row.msgType === 1' type='success'>系统公告</el-tag>
                                <el-tag v-if='scope.row.msgType === 2' type='normal'>系统通知</el-tag>
                            </template>
                        </el-table-column>

                        <el-table-column prop="createTime" width="180"></el-table-column>
                        <el-table-column width="250">
                            <template slot-scope="scope">
                                <el-button size="small" type='success' @click="showDetail(scope.row)">查看</el-button>
                                <el-button size="small" type='primary' @click="handleRead(scope.row)">标为已读</el-button>
                                <el-button type="danger" @click="handleDel(scope.row, 1)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div style='display: flex;justify-content: flex-end'>
                        <el-pagination
                            @size-change='sizeChange1'
                            @current-change='currentChange1'
                            layout='sizes, prev, pager, next, jumper, ->, total, slot'
                            :total='unreadNum'>
                        </el-pagination>
                    </div>
                    <div class="handle-row">
                        <el-button type="primary" @click='handleReadAll'>全部标为已读</el-button>
                    </div>
                </el-tab-pane>
                <el-tab-pane :label="`已读消息(${readNum})`" name="second" @click='initReadList'>
                    <template v-if="message === 'second'">
                        <el-table :data="read" :show-header="false" style="width: 100%;height: 500px;">
                            <el-table-column v-if='false'>
                                <template slot-scope='scope'>
                                    <span>{{scope.row.id}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column>
                                <template slot-scope="scope">
                                    <span class="message-title">{{scope.row.title}}</span>
                                </template>
                            </el-table-column>

                            <el-table-column prop='priority'>
                                <template slot-scope="scope">
                                    <el-tag v-if='scope.row.priority === 1' type='success'>普通</el-tag>
                                    <el-tag v-if='scope.row.priority === 2' type='normal'>重要</el-tag>
                                    <el-tag v-if='scope.row.priority === 3' type='danger'>紧急</el-tag>
                                </template>
                            </el-table-column>

                            <el-table-column prop='msgType'>
                                <template slot-scope="scope">
                                    <el-tag v-if='scope.row.msgType === 1' type='success'>系统公告</el-tag>
                                    <el-tag v-if='scope.row.msgType === 2' type='normal'>系统通知</el-tag>
                                </template>
                            </el-table-column>

                            <el-table-column prop="createTime" width="150"></el-table-column>
                            <el-table-column width="180">
                                <template slot-scope="scope">
                                    <el-button size="small" type='success' @click="showDetail(scope.row)">查看</el-button>
                                    <el-button type="danger" @click="handleDel(scope.row, 1)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div style='display: flex;justify-content: flex-end'>
                            <el-pagination
                                @size-change='sizeChange2'
                                @current-change='currentChange2'
                                layout='sizes, prev, pager, next, jumper, ->, total, slot'
                                :total='readNum'>
                            </el-pagination>
                        </div>
                        <div class="handle-row">
                            <el-button type="danger" @click='logicDeleteAll'>删除全部</el-button>
                        </div>
                    </template>
                </el-tab-pane>

                <el-tab-pane :label="`已发消息(${sendNum})`" name="third" @click='initSendList'>
                    <template v-if="message === 'third'">
                        <el-table :data="sendList" :show-header="false" style="width: 100%;height: 500px;">
                            <el-table-column v-if='false'>
                                <template slot-scope='scope'>
                                    <span>{{scope.row.id}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column>
                                <template slot-scope="scope">
                                    <span class="message-title">{{scope.row.title}}</span>
                                </template>
                            </el-table-column>

                            <el-table-column prop='priority'>
                                <template slot-scope="scope">
                                    <el-tag v-if='scope.row.priority === 1' type='success'>普通</el-tag>
                                    <el-tag v-if='scope.row.priority === 2' type='normal'>重要</el-tag>
                                    <el-tag v-if='scope.row.priority === 3' type='danger'>紧急</el-tag>
                                </template>
                            </el-table-column>

                            <el-table-column prop='msgType'>
                                <template slot-scope="scope">
                                    <el-tag v-if='scope.row.msgType === 1' type='success'>系统公告</el-tag>
                                    <el-tag v-if='scope.row.msgType === 2' type='normal'>系统通知</el-tag>
                                </template>
                            </el-table-column>

                            <el-table-column prop="createTime" width="150"></el-table-column>
                            <el-table-column width="180">
                                <template slot-scope="scope">
                                    <el-button size="small" type='success' @click="showDetail(scope.row)">查看</el-button>
<!--                                    <el-button type="danger" @click="handleDel(scope.row, 1)">删除</el-button>-->
                                </template>
                            </el-table-column>
                        </el-table>
                        <div style='display: flex;justify-content: flex-end'>
                            <el-pagination
                                @size-change='sizeChange3'
                                @current-change='currentChange3'
                                layout='sizes, prev, pager, next, jumper, ->, total, slot'
                                :total='sendNum'>
                            </el-pagination>
                        </div>
<!--                        <div class="handle-row">
                            <el-button type="danger" @click='logicDeleteAll'>删除全部</el-button>
                        </div>-->
                    </template>
                </el-tab-pane>

                <el-tab-pane :label="`回收站(${recycleNum})`" name="forth">
                    <template v-if="message === 'forth'">
                        <el-table :data="recycle" :show-header="false" style="width: 100%;height: 500px;">
                            <el-table-column v-if='false'>
                                <template slot-scope='scope'>
                                    <span>{{scope.row.id}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column>
                                <template slot-scope="scope">
                                    <span class="message-title">{{scope.row.title}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop='priority'>
                                <template slot-scope="scope">
                                    <el-tag v-if='scope.row.priority === 1' type='success'>普通</el-tag>
                                    <el-tag v-if='scope.row.priority === 2' type='normal'>重要</el-tag>
                                    <el-tag v-if='scope.row.priority === 3' type='danger'>紧急</el-tag>
                                </template>
                            </el-table-column>

                            <el-table-column prop='msgType'>
                                <template slot-scope="scope">
                                    <el-tag v-if='scope.row.msgType === 1' type='success'>系统公告</el-tag>
                                    <el-tag v-if='scope.row.msgType === 2' type='normal'>系统通知</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="createTime" width="150"></el-table-column>
                            <el-table-column width="220">
                                <template slot-scope="scope">
                                    <el-button size="small" type='success' @click="showDetail(scope.row)">查看</el-button>
                                    <el-button type="danger" @click="handleDel(scope.row, 2)">删除</el-button>
                                    <el-button @click="handleRestore(scope.row)">还原</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div style='display: flex;justify-content: flex-end'>
                            <el-pagination
                                @size-change='sizeChange4'
                                @current-change='currentChange4'
                                layout='sizes, prev, pager, next, jumper, ->, total, slot'
                                :total='recycleNum'>
                            </el-pagination>
                        </div>
                        <div class="handle-row">
                            <el-button type="danger" @click='clearRecycle'>清空回收站</el-button>
                        </div>
                    </template>
                </el-tab-pane>
            </el-tabs>
        </div>

        <el-dialog v-dialogDrag
                   custom-class="dialogClass"
                   :title="dialogTitle"
                   :close-on-click-modal="false"
                   :modal-append-to-body="false"
                   :append-to-body="true"
                   :visible.sync="detailDialogVisible"
                   :before-close='saveCancel'
                   width="45%"
                   top="10vh">

            <el-form :model="stationMsgForm" :rules='stationMsgFormRule' ref="stationMsgFormRef" label-width="100px"
                     label-position="left">
                <el-form-item label="ID" prop="id" v-show='false'>
                    <el-input v-model="stationMsgForm.id" type="text"  :disabled='viewMode'></el-input>
                </el-form-item>

                <el-form-item label="优先级" prop="priority">
                    <el-radio-group v-model="stationMsgForm.priority" size="small" :disabled='viewMode'>
                        <el-radio-button label="1">普通</el-radio-button>
                        <el-radio-button label="2">重要</el-radio-button>
                        <el-radio-button label="3">紧急</el-radio-button>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="标题" prop="title">
                    <el-input v-model="stationMsgForm.title" type="text" :disabled='viewMode' placeholder='请输入标题'></el-input>
                </el-form-item>
                <el-form-item label="内容" prop="msgContent">
                    <el-input v-model="stationMsgForm.msgContent" clearable type="textarea" :autosize="{minRows:15,maxRows:30}" :disabled='viewMode'  placeholder='请输入内容'></el-input>
                </el-form-item>

                <el-form-item label="消息类型" prop="msgType">
                    <el-radio-group v-model="stationMsgForm.msgType" size="small" :disabled='viewMode'>
                        <el-radio label="1" border>系统公告</el-radio>
                        <el-radio label="2" border>系统通知</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="发送类型" prop="sendType">
                    <el-radio-group v-model="stationMsgForm.sendType" size='small' :disabled='viewMode' @change='changeSendType'>
                        <el-radio label="1" border>全体成员</el-radio>
                        <el-radio label="2" border>选人发送</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label='发送对象' prop='users' v-show='this.stationMsgForm.sendType === "2"' >
                    <el-select v-model="stationMsgForm.users" multiple placeholder="请选择发送对象" style='width: 100%;'
                               clearable
                               :disabled='viewMode'>
                        <el-option
                            v-for="item in empList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="发布时间" prop="publishTime">
                    <el-date-picker
                        style='width: 100%'
                        :disabled='viewMode'
                        v-model="stationMsgForm.publishTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="saveCancel" v-show='viewMode'>我知道了</el-button>
              <el-button type="primary" v-show='!viewMode' @click='saveStaMsg'>确定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
    import { Message } from 'element-ui';
    import {
        deleteAllStaMsg,
        deleteStaMsg,
        getStaMsgList,
        getStaMsgPageInfo,
        logicDeleteAllStaMsg,
        logicDeleteStaMsg,
        realAllStaMsg,
        updateStaMsg
    } from '@/api/StaMsgApi';
    import { getSendMsgPageInfo, getSendUsers, saveStationMsg } from '../../api/StaMsgApi';

    export default {
        name: 'tabs',
        data() {
            return {
                refreshKey: new Date().getTime(),
                dialogTitle: '站内信详情',
                message: 'first',
                showHeader: false,

                unread: [],
                unreadNum: 0,

                read: [],
                readNum: 0,

                sendList: [],
                sendNum: 0,

                recycle: [],
                recycleNum: 0,

                pageNum: 1,
                pageSize: 10,

                empList:[],

                detailDialogVisible: false,
                viewMode: false,

                stationMsgForm: {
                    id: "",
                    priority: 1,
                    title: "",
                    msgContent: "",
                    msgType: "1",
                    sendType: "1",
                    users: [],
                    publishTime: "",
                },

                stationMsgFormRule: {
                    priority: [
                        {required: true, message: '请选择优先级', trigger: 'blur'},
                    ],
                    title: [
                        {required: true, message: '请输入标题', trigger: 'blur'},
                    ],
                    msgContent: [
                        {required: true, message: '请输入内容', trigger: 'blur'},
                    ],
                    msgType:[
                        {required: true, message: '请选择消息类型', trigger: 'blur'},
                    ],
                    sendType: [
                        {required: true, message: '请选择发送类型', trigger: 'blur'},
                    ],
                    users:[
                        {required: true, trigger: 'blur', validator: this.validSendUsers},
                    ],
                    publishTime: [
                        {required: true, message: '请选择发布时间', trigger: 'blur'},
                    ],
                }
            }
        },

        mounted() {
            this.initUnReadList();
            this.initReadList();
            this.initSendList();
            this.initRecycleList();
        },

        methods: {
            addStaMsg() {
                if(this.$refs["stationMsgFormRef" ] !== undefined) {
                    this.$refs["stationMsgFormRef" ].resetFields();
                }
                this.dialogTitle = '新增站内信';
                this.stationMsgForm = {
                    id: "",
                    priority: 1,
                    title: "",
                    msgContent: "",
                    msgType: "1",
                    sendType: "1",
                    users: "",
                    publishTime: "",
                };

                this.viewMode = false;
                this.detailDialogVisible = true;
            },

            saveStaMsg(){
                this.$refs['stationMsgFormRef'].validate((valid) => {
                    if (valid) {
                        let users = [];
                        if (this.stationMsgForm.users.length > 0) {
                            this.stationMsgForm.users.forEach(id => {
                                let obj = this.empList.find(emp => {
                                    //筛选出匹配数据
                                    return emp.id === id;
                                });
                                const user = {'id': obj.id, 'name': obj.name}
                                users.push(user);
                            });
                        }
                        this.stationMsgForm.users = users;
                        const params = this.stationMsgForm;
                        saveStationMsg(params).then(resp => {
                            if (resp && resp.status === 200 && resp.data) {
                                Message.success("保存成功");
                                this.initUnReadList();
                                this.initSendList();
                                this.detailDialogVisible = false;
                            } else {
                                Message.error("保存失败，请联系管理员");
                            }
                        });
                    }
                });
            },

            changeSendType(val) {
                if (val === '2') {
                    getSendUsers().then(resp => {
                       if (resp && resp.status === 200 && resp.data.length > 0) {
                           this.refreshKey = new Date().getTime();
                           this.empList = resp.data;
                       }
                    });
                }
            },
            validSendUsers(rule, value, callback) {
                if (this.stationMsgForm.sendType === '2') {
                    if (value.length === 0) {
                        callback(new Error('请选择发送对象'));
                    }
                }
                callback();
            },

            sizeChange1(size) {
                this.pageNum = 1;
                this.pageSize = size;
                this.initUnReadList();
            },
            currentChange1(page) {
                this.pageNum = page;
                this.initUnReadList();
            },

            sizeChange2(size) {
                this.pageNum = 1;
                this.pageSize = size;
                this.initReadList();
            },
            currentChange2(page) {
                this.pageNum = page;
                this.initReadList();
            },

            sizeChange3(size) {
                this.pageNum = 1;
                this.pageSize = size;
                this.initSendList();
            },
            currentChange3(page) {
                this.pageNum = page;
                this.initSendList()
            },

            sizeChange4(size) {
                this.pageNum = 1;
                this.pageSize = size;
                this.initRecycleList();
            },
            currentChange4(page) {
                this.pageNum = page;
                this.initRecycleList()
            },
            showDetail(row) {
                this.viewMode = true;
                this.stationMsgForm.id = row.id;
                this.stationMsgForm.title = row.title;
                this.stationMsgForm.msgContent = row.msgContent;
                this.stationMsgForm.msgType = row.msgType + "";
                this.stationMsgForm.priority = row.priority;
                this.stationMsgForm.sendType = (row.users && row.users.length === 0) ? '1' : '2';
                let users = (row.users && row.users.length) > 0 ? row.users.map(x => x.name) : [];
                this.stationMsgForm.users = users;
                this.empList = users;
                this.stationMsgForm.publishTime = row.createTime;
                this.refreshKey = new Date().getTime();
                this.detailDialogVisible = true;
            },
            saveCancel() {
                this.detailDialogVisible = false;
            },

            initUnReadList() {
                const params = {'pageNum': this.pageNum, 'pageSize': this.pageSize};
                params.readStatus = 0;
                params.delFlag = 0;
                getStaMsgPageInfo(params).then(resp => {
                    if (resp && resp.status === 200) {
                        this.unread = resp.data.rows;
                        this.unreadNum = resp.data.total;
                    }
                });
            },
            initReadList() {
                const params = {'pageNum': this.pageNum, 'pageSize': this.pageSize};
                params.readStatus = 1;
                params.delFlag = 0;
                getStaMsgPageInfo(params).then(resp => {
                    if (resp && resp.status === 200) {
                        this.read = resp.data.rows;
                        this.readNum = resp.data.total;
                    }
                });
            },
            initSendList() {
                const params = {'pageNum': this.pageNum, 'pageSize': this.pageSize};
                getSendMsgPageInfo(params).then(resp => {
                    if (resp && resp.status === 200) {
                        this.sendList = resp.data.rows;
                        this.sendNum = resp.data.total;
                    }
                });
            },

            initRecycleList() {
                const params = {'pageNum': this.pageNum, 'pageSize': this.pageSize};
                params.delFlag = 1;
                getStaMsgPageInfo(params).then(resp => {
                    if (resp && resp.status === 200) {
                        this.recycle = resp.data.rows;
                        this.recycleNum = resp.data.total;
                    }
                });
            },
            handleRead(row) {
                // const item = this.unread.splice(index, 1);
                // console.log(item);
                // this.read = item.concat(this.read);
                const params = {};
                params.id = row.id;
                params.readStatus = 1;
                updateStaMsg(params).then(resp => {
                    if (resp && resp.status === 200) {
                        this.initUnReadList();
                        this.initReadList();
                        Message.success("标记已读成功！");
                    }
                });
            },
            handleDel(row, type) {
                // const item = this.read.splice(index, 1);
                // this.recycle = item.concat(this.recycle);
                const params = {};
                params.id = row.id;
                if (type === 1) {
                    params.delFlag = 1;
                    logicDeleteStaMsg(params).then(resp => {
                        if (resp && resp.status === 200) {
                            this.initUnReadList();
                            this.initReadList();
                            this.initRecycleList();
                            Message.success("删除成功！");
                        }
                    });
                } else {
                    deleteStaMsg(params).then(resp => {
                        if (resp && resp.status === 200) {
                            this.initUnReadList();
                            this.initReadList();
                            this.initRecycleList();
                            Message.success("删除成功！");
                        }
                    });
                }
            },
            handleRestore(row) {
                // const item = this.recycle.splice(index, 1);
                // this.read = item.concat(this.read);
                const params = {};
                params.id = row.id;
                params.delFlag = 0;
                updateStaMsg(params).then(resp => {
                    if (resp && resp.status === 200) {
                        this.initUnReadList();
                        this.initReadList();
                        this.initRecycleList();
                        Message.success("还原成功！");
                    }
                });
            },
            handleReadAll() {
                const params = {};
                params.readStatus = 1;
                realAllStaMsg(params).then(resp => {
                    if (resp && resp.status === 200) {
                        this.initUnReadList();
                        this.initReadList();
                        this.initRecycleList();
                        Message.success("全部标记已读成功！");
                    }
                });
            },
            logicDeleteAll() {
                logicDeleteAllStaMsg().then(resp => {
                    if (resp && resp.status === 200) {
                        this.initUnReadList();
                        this.initReadList();
                        this.initRecycleList();
                        Message.success("全部删除成功！");
                    }
                });
            },
            clearRecycle() {
                deleteAllStaMsg().then(resp => {
                    if (resp && resp.status === 200) {
                        this.initUnReadList();
                        this.initReadList();
                        this.initRecycleList();
                        Message.success("清空回收站成功！");
                    }
                });
            }
        },
    }
</script>

<style>
.message-title{
    cursor: pointer;
}
.handle-row{
    margin-top: 30px;
}

.container {
    padding: 30px;
    background: #fff;
    border: 1px solid #ddd;
    border-radius: 5px;
}
</style>

